package com.zyp.jobseeker.controller;

import com.zyp.jobseeker.entity.Enterprise;
import com.zyp.jobseeker.entity.Student;
import com.zyp.jobseeker.entity.User;
import com.zyp.jobseeker.enums.UserRole;
import com.zyp.jobseeker.service.UserService;
import com.zyp.jobseeker.service.StudentService;
import com.zyp.jobseeker.service.EnterpriseService;
import com.zyp.jobseeker.utils.JwtUtil;
import com.zyp.jobseeker.utils.PasswordUtil;
import com.zyp.jobseeker.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户Controller
 * 处理用户信息管理相关请求
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private PasswordUtil passwordUtil;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取当前登录用户的详细信息
     */
    @GetMapping("/info")
    @PreAuthorize("hasAnyRole('STUDENT', 'ENTERPRISE', 'ADMIN')")
    public ResultUtil<?> getUserInfo(@RequestHeader("Authorization") String token) {
        try {
//            //验证token是否符合格式
//            if (!jwtUtil.isValidJwtFormat(token)) {
//                return ResultUtil.fail(401, "jwt不符合格式");
//            }
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);

            // 验证token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.fail(401, "认证信息已过期，请重新登录");
            }

            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return ResultUtil.fail(401, "无效的用户ID");
            }

            // 获取用户基本信息
            User user = userService.findById(userId);
            if (user == null) {
                return ResultUtil.fail(404, "用户不存在");
            }

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);

            // 如果是学生，返回学生信息
            if (user.getRole().getCode() == UserRole.STUDENT.getCode()) {
                studentService.findById(userId).ifPresent(student -> result.put("studentInfo", student));
            }
            // 如果是企业，返回企业信息
            else if (user.getRole().getCode() == UserRole.ENTERPRISE.getCode()) {
                enterpriseService.findById(userId).ifPresent(enterprise -> result.put("enterpriseInfo", enterprise));
            }

            return ResultUtil.success("获取用户信息成功", result);
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return ResultUtil.fail(500, "获取用户信息失败: " + e.getMessage());
        }
    }
    /**
     * 根据id获取用户信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAnyRole('STUDENT', 'ENTERPRISE', 'ADMIN')")
    public ResultUtil<?> getUserInfoById(@PathVariable Long id) {
        try {
            User user = userService.findById(id);
            if (user == null) {
                return ResultUtil.fail(404, "用户不存在");
            }
            Map<String, Object> result = new HashMap<>();
            result.put("user", user);
            if (user.getRole().getCode() == UserRole.STUDENT.getCode()) {
                studentService.findById(id).ifPresent(student -> result.put("studentInfo", student));
                return ResultUtil.success("获取学生用户信息成功", result);
            } else if (user.getRole().getCode()==UserRole.ENTERPRISE.getCode()){
                enterpriseService.findById(id).ifPresent(enterprise -> result.put("enterpriseInfo", enterprise));
                return ResultUtil.success("获取企业用户信息成功", result);
            }
            //用户角色不是学生也不是企业，没找到用户，返回错误结果
            return ResultUtil.fail(404, "用户不存在");
        }
        catch (Exception e) {
            return ResultUtil.fail(500, "获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 修改用户密码
     */
    @PutMapping("/password")
    @PreAuthorize("hasAnyRole('STUDENT', 'ENTERPRISE', 'ADMIN')")
    public ResultUtil<?> updatePassword(@RequestHeader("Authorization") String token, @RequestBody Map<String, Object> passwordInfo) {
        try {
            // 从请求头中获取token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);

            // 验证token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.fail(401, "认证信息已过期，请重新登录");
            }

            // 从token中获取用户ID
            Long userId = jwtUtil.getUserIdFromToken(token);
            if (userId == null) {
                return ResultUtil.fail(401, "无效的用户ID");
            }

            // 获取用户基本信息
            User user = userService.findById(userId);
            if (user == null) {
                return ResultUtil.fail(404, "用户不存在");
            }

            // 获取旧密码和新密码
            String oldPassword = (String) passwordInfo.get("oldPassword");
            String newPassword = (String) passwordInfo.get("newPassword");

            // 验证旧密码是否正确
            if (!passwordUtil.matchesPassword(oldPassword, user.getPassword())) {
                return ResultUtil.fail("原密码不正确");
            }
            user.setPassword(passwordUtil.encodePassword(newPassword));
            userService.updatePassword(user.getId(),oldPassword, user.getPassword());

            return ResultUtil.success("密码修改成功");
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return ResultUtil.fail(500, "密码修改失败: " + e.getMessage());
        }
    }
}
